package com.jn.picasso.views;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.jn.picasso.R;
import com.jn.picasso.base.BaseActivity;
import com.jn.picasso.contract.StarContract;
import com.jn.picasso.entity.StarEntity;
import com.jn.picasso.presenter.StarPresenter;
import com.jn.picasso.utils.LogUtils;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.ArrayList;
import java.util.List;

public class StarActivity extends BaseActivity
        implements StarContract.IStarView, View.OnClickListener {

    private Button mButton;
    private TextView mText;
    private ImageView mImage;
    private ImageView mImage2;
    private StarContract.IStarPresenter mPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_star;
    }

    @Override
    public void init() {
        mButton = findViewById(R.id.button);
        mText = findViewById(R.id.text);
        mImage = findViewById(R.id.image);
        mImage2 = findViewById(R.id.image2);
        mButton.setOnClickListener(this);
        mPresenter = new StarPresenter(this);
    }

    @Override
    public void showData(StarEntity star) {
        if (star != null) {
            String url = star.getData().getCover().replace("http", "https");
            LogUtils.d("asdf", "star : " + url);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("歌名 : ").append(star.getData().getSong()).append("\n");
            stringBuilder.append("歌手 : ").append(star.getData().getSinger());
            mText.setText(stringBuilder.toString());

            List<Transformation> transformations = new ArrayList<>();
            transformations.add(new GrayTransformation());
            transformations.add(new WatermarkTransformation("吉林农业科技学院"));

            Picasso.get()
                    .load(url)
                    //.resize(600, 880)//重置尺寸
                    //.centerCrop()//居中裁剪，配合resize使用
                    //.centerInside()
                    //.rotate(90)//旋转
                    //.placeholder(R.mipmap.loding)//未加载出图片时设置的占位图片
                    //.noFade()//无过度动画
                    //.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)//不缓存
                    //.transform(transformations)
                    .tag(this)
                    .into(mImage);
            Picasso.get()
                    .load(url)
                    //.fit()//适应ImageView尺寸
                    //.resizeDimen(R.dimen.image_width, R.dimen.image_height) //重置尺寸,不能和fit同时使用
                    //.onlyScaleDown()//只有尺寸缩小的时候，resize才生效
                    //.noPlaceholder()//不设置占位图片,和placeholder方法不能同时使用
                    //.error(R.mipmap.error)
                    //.networkPolicy(NetworkPolicy.OFFLINE)
                    //.transform(new WatermarkTransformation("计算机"))
                    //.transform(new RoundedWithGradientTransformation(20, 500))
                    //.transform(new VintageFilterTransformation())
                    //.transform(new GrayTransformation())
                    .tag(this)
                    .priority(Picasso.Priority.HIGH) // 高优先级（默认NORMAL）
                    .into(mImage2);
        } else {
            showToast("未查到数据，请输入正确单号！");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消所有关联到当前Activity的请求
        Picasso.get().cancelTag(this);
    }

    @Override
    public void onHttpLoading(boolean loading) {

    }

    @Override
    public void onHttpFail(String... msg) {

    }

    @Override
    public void onHttpTimeout() {

    }

    @Override
    public void onHttpTokenExpiration() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.button) {
            mPresenter.getData();
        }
    }

    public static class WatermarkTransformation implements Transformation {//添加水印
        private String watermarkText;

        // 构造方法：传入水印文字
        public WatermarkTransformation(String text) {
            this.watermarkText = text;
        }

        @Override
        public Bitmap transform(Bitmap source) {
            // 创建一个新的 Bitmap（与原图尺寸相同）
            Bitmap result = Bitmap.createBitmap(
                    source.getWidth(),
                    source.getHeight(),
                    source.getConfig()
            );

            // 创建画布，绘制原始图片
            Canvas canvas = new Canvas(result);
            canvas.drawBitmap(source, 0, 0, null);

            // 配置画笔（水印文字）
            Paint paint = new Paint();
            paint.setColor(Color.WHITE);
            paint.setTextSize(40);
            paint.setAlpha(180); // 半透明

            // 计算文字位置（右下角，留出边距）
            float x = source.getWidth() - paint.measureText(watermarkText) - 20;
            float y = source.getHeight() - 20;

            // 绘制水印
            canvas.drawText(watermarkText, x, y, paint);

            // 回收原始 Bitmap，避免内存泄漏
            if (source != result) {
                source.recycle();
            }

            return result;
        }

        @Override
        public String key() {
            // 水印文字不同，缓存 key 也不同（确保正确缓存）
            return "watermark_" + watermarkText;
        }
    }

    public static class GrayTransformation implements Transformation {//黑白

        @Override
        public Bitmap transform(Bitmap source) {
            int width, height;
            height = source.getHeight();
            width = source.getWidth();

            Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            Canvas c = new Canvas(bmpGrayscale);
            Paint paint = new Paint();
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0);
            ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
            paint.setColorFilter(f);
            c.drawBitmap(source, 0, 0, paint);

            if (source != null && source != bmpGrayscale) {
                source.recycle();
            }
            return bmpGrayscale;
        }

        @Override
        public String key() {
            return "gray";
        }
    }

    public class RoundedWithGradientTransformation implements Transformation {//图片圆角 + 顶部渐变遮罩
        private int cornerRadius; // 圆角半径
        private int gradientHeight; // 渐变高度

        public RoundedWithGradientTransformation(int cornerRadius, int gradientHeight) {
            this.cornerRadius = cornerRadius;
            this.gradientHeight = gradientHeight;
        }

        @Override
        public Bitmap transform(Bitmap source) {
            int width = source.getWidth();
            int height = source.getHeight();

            // 创建带透明通道的结果图
            Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(result);

            // 1. 绘制圆角矩形遮罩
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            RectF rect = new RectF(0, 0, width, height);
            canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint);

            // 2. 用原图裁剪出圆角效果（SRC_IN模式）
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(source, 0, 0, paint);

            // 3. 绘制顶部渐变遮罩（从黑色半透明到透明）
            paint.setXfermode(null); // 重置混合模式
            LinearGradient gradient = new LinearGradient(
                    0, 0, 0, gradientHeight,
                    new int[]{0xCC000000, 0x00000000}, // 颜色从深到浅
                    null, Shader.TileMode.CLAMP
            );
            paint.setShader(gradient);
            canvas.drawRect(0, 0, width, gradientHeight, paint);

            if (source != result) {
                source.recycle();
            }
            return result;
        }

        @Override
        public String key() {
            return "rounded_gradient_" + cornerRadius + "_" + gradientHeight;
        }
    }

    public static class VintageFilterTransformation implements Transformation {//复古

        @Override
        public Bitmap transform(Bitmap source) {
            // 创建颜色矩阵，调整RGB比例实现复古效果
            ColorMatrix matrix = new ColorMatrix();
            // 降低蓝色通道，增强红色和绿色通道
            matrix.set(new float[]{
                    0.627f, 0.320f, 0.050f, 0, 0,  // 红色通道
                    0.098f, 0.914f, 0.008f, 0, 0,  // 绿色通道
                    0.213f, 0.315f, 0.472f, 0, 0,  // 蓝色通道
                    0, 0, 0, 1, 0   // 透明度
            });

            // 应用颜色矩阵
            Bitmap result = Bitmap.createBitmap(
                    source.getWidth(),
                    source.getHeight(),
                    source.getConfig()
            );
            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setColorFilter(new ColorMatrixColorFilter(matrix));
            canvas.drawBitmap(source, 0, 0, paint);

            if (source != result) {
                source.recycle();
            }
            return result;
        }

        @Override
        public String key() {
            return "vintage_filter";
        }
    }
}